<template>
  <div class="table-bottom table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal"> </FilterTable>
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerLeft>
          <a-space>
            <a-button class="gray-outline" @click="publish('mul')">提交刊登</a-button>
            <a-button class="gray-outline" @click="del">删除</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table :data="tableData" size="mini" row-key="spu" v-model:selected-keys="ids" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" class="table-single-line" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ rowIndex }" :width="30">{{ rowIndex + 1 }}</a-table-column>
              <a-table-column title="图片" #cell="{ record }" :width="40">
                <!-- <ImgPopover :src="imgUrl(record)">
                  <template #con>
                    <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(record)" />
                  </template>
                </ImgPopover> -->
                <a-image @click="showBigImg(record)" width="40" height="40" fit="contain" :preview="false" :src="imgUrl(record)" />
              </a-table-column>
              <a-table-column title="SPU" #cell="{ record }" :width="60">
                <div @click="showDetail(record)">
                  <TextLimit class="highlight cursor" position="top" :rows="1" :val="record.spu || '--'"></TextLimit>
                </div>
              </a-table-column>
              <a-table-column title="SKU" #cell="{ record }" :width="40">
                <skuListPopover :data="record" :type="1" />
              </a-table-column>
              <a-table-column title="原URL" #cell="{ record }" :width="40">
                <!-- <skuListPopover :list="record" :type="1" /> -->
                <!-- {{ getSaleType(record) }} -->

                <a-popover v-if="record.mallSourceUrl">
                  <icon-link style="font-size: 18px" class="highlight cursor" @click="jump(record)" />
                  <template #content>
                    <p>{{ record.mallSourceUrl }}</p>
                  </template>
                </a-popover>
              </a-table-column>

              <a-table-column title="起订量" #cell="{ record }" :width="40">
                <!-- <skuListPopover :list="record" :type="1" /> -->
                {{ getSaleType(record) == '一口价' ? getNum(record) : '' }}
              </a-table-column>

              <a-table-column title="售价" #cell="{ record }" :width="80">
                <div v-if="getSaleType(record) != '一口价'" v-for="(item, index) of getMetaDataArr(record)" :key="index">
                  <span>{{ item.min }}</span>
                  <span>-</span>
                  <span>{{ item.max }}</span>
                  <span>：</span>
                  <span>${{ item.formatPrice }}</span>
                </div>
              </a-table-column>
              <a-table-column title="类目" #cell="{ record }" :width="80">
                {{ $extract(record, 'category.name') }}
              </a-table-column>
              <a-table-column title="产品名称" #cell="{ record }" :width="120">
                <TextLimit position="top" :rows="1" :val="record.spuName || '--'"></TextLimit>
              </a-table-column>
              <a-table-column title="标签" #cell="{ record }" :width="120">
                <TextLimit position="top" :rows="1" :val="getTagName(record) || '--'"></TextLimit>
              </a-table-column>
              <a-table-column title="产品属性" #cell="{ record }" :width="80">
                <!-- <productPre :list="record" /> -->
                <perPopover :info="record" />
              </a-table-column>
              <!-- <a-table-column title="产品来源" #cell="{ record }" :width="80"></a-table-column> -->
              <a-table-column title="产品更新时间" #cell="{ record }" :width="90">
                {{ $setTime(record.gmtWrite) }}
              </a-table-column>
              <a-table-column title="未刊登店铺" #cell="{ record }" :width="80">
                <TextLimit position="top" :rows="1" :val="getShopName(record) || '--'"></TextLimit>
              </a-table-column>
              <a-table-column title="操作" #cell="{ record }" :width="40">
                <a-space>
                  <a-button type="text" @click="publish('single', record.spu)">去刊登</a-button>
                </a-space>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>

  <toPublish v-if="showToPublish" v-model="showToPublish" :ids="ids" @save="getList" />

  <!-- 图片查看 -->
  <a-image-preview-group v-model:visible="visible" v-model:current="current" infinite :srcList="previewList" />
  <!-- spu详情 -->
  <ShowSpuDetail ref="showSpuDetail" :detail="detail" />
</template>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { pageRelatedV2, getCategoryList, batchUpdateSkipNullById } from '@/api/product'
  import { findShopPageByParam } from '@/api/system'
  import { Modal } from '@arco-design/web-vue'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import skuListPopover from './components/productVariantListPopover.vue'
  import toPublish from './components/toPublish.vue'
  import perPopover from './components/perPopover.vue'
  import ShowSpuDetail from '@/views/product/productManagement/productList/componetns/showSpuDetail.vue'

  let pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })
  let loading = ref(false)
  let showToPublish = ref(false)
  let visible = ref(false)
  let current = ref(0)
  let previewList = ref([])
  let detail = ref({ type: '', data: {} })
  let ids = ref([])
  let tableData = ref([])
  let shopList = ref([])
  let searchValue = ref({})
  const showSpuDetail = ref()
  const filterItem: any = ref([
    {
      type: 'input_search',
      key: 'spuName',
      keyWidth: '90',
      value: ref(),
      placeholder: '请输入产品名称',
      label: '产品名称',
      width: 200,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'spuList',
      keyItems: [
        { label: 'SPU', value: 'spuList' },
        { label: 'SKU', value: 'skuList' },
      ],
      keyWidth: '80',
      value: ref(),
      placeholder: '请输入',
      label: '任务ID',
      width: 160,
    },
    // {
    //   key: 'taskType',
    //   label: '产品来源',
    //   value: ref(),
    //   type: 'select',
    //   width: 140,
    //   optionItems: [
    //     { label: '自营', value: '自营' },
    //     { label: '1688', value: '1688' },
    //     { label: 'Amazon', value: 'Amazon' },
    //     { label: '梅陇在线', value: '梅陇在线' },
    //     { label: '其他', value: '其他' },
    //   ],
    // },
    {
      type: 'cascader',
      key: 'categoryIdList',
      optionItems: [],
      keyWidth: '120',
      value: ref(),
      placeholder: '商品分类',
      label: '类目',
      width: 200,
      isMultiple: true,
    },
  ])

  // 图片
  const imgUrl = (info: any) => {
    let arr = info.productPicList || []
    return arr[0]?.url || ''
  }

  // 搜索
  const searchByVal = (info: any) => {
    searchValue.value = info
    getList()
  }
  // 分页
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const getList = async () => {
    let params: any = {
      ...searchValue.value,
      needCount: true,
      filterWooCommerceClaim: true,
      needSkuData: true,
      needFillPropData: true,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }

    if (params.spuList) {
      params.spuList = params.spuList.split(',')
    } else {
      delete params.spuList
    }

    if (params.skuList) {
      params.skuList = params.skuList.split(',')
    } else {
      delete params.skuList
    }

    if (params.categoryIdList) {
      params.categoryIdList = params.categoryIdList.split(',')
    } else {
      delete params.categoryIdList
    }

    loading.value = true
    const res: any = await pageRelatedV2(params)
    pageNation.value.total = res.data.total
    tableData.value = res?.data?.list
    ids.value = []
    loading.value = false
  }

  const getCategory = async () => {
    const res: any = await getCategoryList()
    filterItem.value[2].optionItems = res.data
  }

  const getTagName = (data: any) => {
    let arr = data?.tagList || []
    return arr.map((item: any) => item.name).join('，')
  }
  const getShopName = (data: any) => {
    let resArr: any = []
    let arr = data?.wooCommerceVersionClaimLogList || []
    shopList.value.forEach((e: any) => {
      let item = arr.find((el: any) => el.shopId == e.id)
      if (!item) resArr.push(e)
    })
    return resArr.map((item: any) => item.shopName).join('，')
  }

  const publish = (type: string, id?: string) => {
    if (type == 'mul' && ids.value.length <= 0) return Message.error('请选择要刊登的产品')
    if (id) ids.value = [id]
    showToPublish.value = true
  }

  const getSaleType = (data: any) => {
    let item = (data?.productSkuList && data?.productSkuList[0]) || {}
    if (item.mallPriceType == 'fixed_price') {
      return '一口价'
    } else if (item.mallPriceType == 'ladder_price') {
      return '阶梯价'
    } else {
      return ''
    }
  }
  const getNum = (data: any) => {
    let item = (data?.productSkuList && data?.productSkuList[0]) || {}
    return item.currencyRule
  }

  const getMetaDataArr = (data: any) => {
    let item = (data?.productSkuList && data?.productSkuList[0]) || {}
    let str = item.mallPriceRangeList
    return item.mallPriceRangeList || []
  }

  // 获取店铺信息
  const getShopLsit = async () => {
    let params = {
      pageSize: 999999,
      platform: 'wooCommerce',
    }
    const res: any = await findShopPageByParam(params)
    if (res) {
      let arr = res.data?.records || []
      shopList.value = arr
    }
  }

  const del = () => {
    if (ids.value.length <= 0) return Message.error('请选择数据')
    Modal.error({
      title: '删除',
      content: '请再次确认是否需要删除',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        let params: any = {
          updateDocList: [],
        }

        ids.value.forEach((e) => {
          let item: any = tableData.value.find((el: any) => el.spu == e)
          let obj = {
            id: item ? item.id : '',
            wooCommerceVersionHidden: true,
          }
          params.updateDocList.push(obj)
        })

        const res: any = await batchUpdateSkipNullById(params)
        if (res.code == 'SUCCESS') {
          Message.success('删除成功')
          ids.value = []
          getList()
        }
      },
    })
  }

  const showBigImg = (data: any) => {
    let arr = data?.productPicList || []
    console.log(arr)

    previewList.value = arr.map((e: any) => e.url)
    current.value = 0
    visible.value = true
  }

  // 查看详情
  const showDetail = (data: any) => {
    detail.value.data = data
    showSpuDetail.value.visible = true
  }

  const jump = (data: any) => {
    let url = data?.mallSourceUrl || ''
    window.open(url)
  }

  onMounted(async () => {
    await getShopLsit()
    await getList()
    await getCategory()
  })
</script>

<style lang="less" scoped>
  .table-bottom {
    height: calc(100vh - @menuAndTabHeight);
    .search-w {
      width: 100%;
      background-color: white;
      padding: 10px 0 1px 0;
      box-sizing: border-box;
    }
  }
</style>
